<template>
  <div>
    <!-- 添加的按钮   -->
    <el-button type="primary" icon="el-icon-plus" style="margin: 10px 0" @click="addTradeMark('add')">添加</el-button>
    <!-- 表格区域 -->
    <el-table :data="list" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO" width="width">
        <template slot-scope="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="width">
        <template slot-scope="{ row, $index }">
          <el-button type="warning" size="mini" icon="el-icon-edit" @click="updateTradeMark(row, 'update')">修改
          </el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteTradeMark(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <!-- :current-page="1"   表示当前页-->
    <!-- :page-size="5"  表示每页几条数据 -->
    <!-- :page-sizes="[3, 5, 7, 9]"  可以设置每页显示几条数据 -->
    <!-- layout=" prev, pager, next, jumper,->,sizes, total"  设置分页组件的布局 -->
    <!-- :total="0"  总数据条数 -->
    <!-- handleCurrentChange  当前页变化触发 -->
    <!-- handleSizeChange  每页多少条数据发生变化触发 -->
    <el-pagination style="margin-top: 20px; textalign: center" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" :current-page="page" :page-sizes="[3, 5, 10]" :page-size="limit"
      :page-count="7" layout=" prev, pager, next, jumper,->,sizes, total" :total="total">
    </el-pagination>
    <!-- 点击添加,修改按钮弹出的对话框 -->
    <el-dialog :title="textMap[dialogStatus] + '品牌'" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form :model="tmForm" :rules="tmFormrules" ref="tmFormRuleForm" style="width: 80%">
        <el-form-item prop="tmName" label="品牌名称" label-width="90px">
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>
        <!-- 这里收集数据不能使用v-model，因为不是表单元素 
          :on-success="handleAvatarSuccess"  图片上传成功后执行的函数
          :before-upload="beforeAvatarUpload" 图片上传之前执行的函数
        -->
        <el-form-item prop="logoUrl" label="品牌LOGO" label-width="100px">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateTradeMark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "tradeMark",
  data() {
    return {
      //代表分页器第几页
      page: 1,
      //当前页数展示数据条数
      limit: 3,
      //总数据条数
      total: 0,
      //存放列表数据
      list: [],
      //控制添加，修改对话框的显示与隐藏
      dialogFormVisible: false,
      //收集表单信息
      tmForm: {
        tmName: "",
        logoUrl: "",
      },
      //表单的验证规则对象
      tmFormrules: {
        tmName: [
          {
            required: true,
            message: "请输入品牌名称",
            trigger: "blur",
          },
          {
            min: 1,
            max: 6,
            message: "长度在 1 到 6 个字符",
            trigger: "blur",
          },
        ],
        logoUrl: [
          {
            required: true,
            message: "请选择品牌LOGO",
            trigger: "change",
          },
        ],
      },
      dialogStatus: "",
      textMap: {
        add: "添加",
        update: "修改",
      },
    };
  },
  mounted() {
    //组件已挂载完毕就发送请求
    this.getPageList();
  },
  methods: {
    //获取品牌管理列表数据
    async getPageList() {
      //发起请求
      //解构出需要携带的参数
      const { page, limit } = this;
      let result = await this.$API.tradeMark.reqTradeMarkList(page, limit);
      console.log(result);
      if (result.code == 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    //每页展示多少条数据发生变化触发的事件
    handleSizeChange(limit) {
      this.limit = limit;
      this.getPageList();
    },
    //当前页发生变化触发的事件
    handleCurrentChange(page) {
      console.log(page);
      this.page = page;
      this.getPageList();
    },
    //点击添加按钮触发的事件
    addTradeMark(dialogStatus) {
      console.log(dialogStatus);
      this.dialogStatus = dialogStatus;
      this.dialogFormVisible = true;
    },
    //点击修改按钮触发的事件
    updateTradeMark(row, dialogStatus) {
      console.log(row, "44444");
      this.dialogStatus = dialogStatus;
      this.dialogFormVisible = true;
      this.tmForm = {
        ...row,
      }; //浅拷贝
    },
    //图片上传成功触发的函数
    handleAvatarSuccess(res, file) {
      console.log(res, "服务器返回的数据");
      //把图片真实的url地址给表单数据logoUrl
      this.tmForm.logoUrl = res.data;
    },
    //图片上传之前触发的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //对话框关闭，清空表单
    closeDialog() {
      this.tmForm = {};
    },
    //点击添加/修改对话框的确定按钮触发的事件
    addOrUpdateTradeMark() {
      //提交表单数据发送请求前的预验证
      this.$refs.tmFormRuleForm.validate(async (valid) => {
        if (!valid) return false;
        //发送请求:  添加品牌/修改品牌
        let result = await this.$API.tradeMark.reqAddOrUpdateTradeMark(
          this.tmForm
        );
        if (result.code == 200) {
          this.$message.success(
            this.tmForm.id ? "修改品牌成功" : "添加品牌成功"
          );
          //当时添加品牌时停留在第一页，修改品牌停留在当前页
          this.getPageList(this.tmForm.id ? this.page : 1);
          this.dialogFormVisible = false;
        }
      });
    },
    //点击删除按钮触发的函数
    async deleteTradeMark(id) {
      console.log(id, "454545");
      const result = await this.$confirm(
        "此操作将永久删除该品牌, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        return error;
      });
      console.log(result, "66666");
      if (result !== "confirm") {
        return this.$message.info("用户取消了删除");
      } else {
        //发起删除品牌的请求
        const res = await this.$API.tradeMark.reqDeleteTradeMark(id);
        console.log(res, "99999");
        if (res.code !== 200) {
          return this.$message.error("品牌删除失败");
        }
        this.$message.success("品牌删除成功");
        this.getPageList();
      }
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
